package com.azt.front.action.wechat;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.azt.api.pojo.Dictionary;
import com.azt.api.pojo.SignUp;
import com.azt.api.service.ConfigService;
import com.azt.api.service.DictionaryService;
import com.azt.api.service.SignUpAdminService;
import com.azt.api.service.SignUpService;
import com.azt.exception.ServiceException;
import com.azt.model.AjaxJson;
import com.azt.service.wechat.WeChatConstant;
import com.azt.service.wechat.WeChatService;

/**
 * WeChat 回调
 * Created by LiQZ on 2017/3/30.
 */
@Controller
public class SignUpAdminAction {

    private static final Logger logger = LoggerFactory.getLogger(SignUpAdminAction.class);

    @Autowired
    private SignUpAdminService signUpAdminService;

    @Autowired
	private WeChatService weChatService;
    
    @Autowired
    private SignUpService signUpService;
    
	@Autowired
	private DictionaryService dictionaryService;
    
	@Autowired
	private ConfigService configService;

    
    @RequestMapping("/pressconference/addconferenceadmin")
    public String addAdmin(String code, String secret, Model model) {
        logger.info("WeChat cell back secret {} code {}", secret, code);
        // 保存用户信息
        String message = "增加管理员成功";
        try {
            signUpAdminService.saveAdmin(code, secret);
        } catch (ServiceException e) {
            message = e.getMessage();
        }
        model.addAttribute("message", message);
        return "wechat/conference/close_message";
    }
    
    
	//用户展示二维码页面
	@RequestMapping(value="pressconference/z/{id}", method=RequestMethod.GET)
	public String qrcord(@PathVariable Integer id, ModelMap model){
		SignUp signUpBy = signUpService.getSignUpById(id);
		if(signUpBy!=null){
			model.addAttribute("signUp", signUpBy);
			
			//授权登陆开关
			Boolean auth=WeChatConstant.AUTH;
			//授权登陆
			String redirectUrl=WeChatConstant.getQRCodeRedirectUrl(id);
			String showWechatUrl=WeChatConstant.getShowWechatBase(redirectUrl);
			
			if(auth){
				redirectUrl=showWechatUrl;
				try {
					showWechatUrl=URLEncoder.encode(showWechatUrl,"utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}else{
				//跳转到口令页面
				//redirectUrl +="&secret=" + WeChatConstant.SECRET;
				redirectUrl="/pressconference/secretCommand";
			}
			
				model.addAttribute("redirectUrl", redirectUrl);
			
		}
		
		return "wechat/conference/signQRcord";
	}
    
	
	//口令页面
	@RequestMapping("/pressconference/secretCommand")
	public String secretCommand(Integer id,ModelMap model){
		model.addAttribute("id", id);
		return "wechat/conference/secretcommand";
	}
	
	//验证口令
	@ResponseBody
	@RequestMapping("/pressconference/validateCommand")
	public AjaxJson validateCommand(String koul){
		String signword = configService.getConfigValueByCode("SIGN_WORD");
		if(signword!=null){
			if(signword.equals(koul)){
				return AjaxJson.success();
			}else{
				return AjaxJson.error("口令不正确");
			}
		}else{
			return AjaxJson.error("没有配置口令");
		}
	}
    
    
	//扫描二维码图片请求
	@RequestMapping("/pressconference/scanseatqrcode")
	public String scanseatqrcode(Integer id,String secret,String code,ModelMap model){
		//是否使用测试
		int err=0;
		boolean authenticated = false;
		if (secret != null && secret.equals(WeChatConstant.SECRET)) {
			authenticated = true;
		}
		//没有使用测试，使用授权登录
		if (!authenticated) {
			if(StringUtils.isNotBlank(code)){
				JSONObject openInfo=weChatService.getAccessToken(WeChatConstant.MOBILE_APP_ID, WeChatConstant.MOBLE_SECRET, code);
				if (openInfo == null) {
					err=1;
					return "wechat/conference/signupscanseat";
				}
			}else{
				err=1;
				return "wechat/conference/signupscanseat";
			}
		
		}
		
		model.addAttribute("err", err);
		
		SignUp signUpBy = signUpService.getSignUpById(id);
		if(signUpBy!=null){
			//报名成功
			if(err==0){
				signUpBy.setSeatConfirm(1);
				signUpService.saveOrUpdateSignUp(signUpBy);
			}
		}
		model.addAttribute("signUp", signUpBy);
	
		
		return "wechat/conference/signupscanseat";
	}

}
